#include <iostream>
#include <string>
#include <sstream>
using namespace std;

const int max_value = 10000 + 10;

int n, leaf_value, leaf_path_sum;
int in_order[max_value], post_order[max_value], l_child[max_value], r_child[max_value];

bool read_input(int *a) {
  string str;
  if (!getline(cin, str)) {
    return false;
  }
  stringstream ss(str);
  n = 0;
  int x;
  while (ss >> x) {
    a[n++] = x;
  }
  return n > 0;
}

int construct(int in_l, int in_r, int post_l, int post_r) {
  if (in_l > in_r) {
    return 0;
  }
  int root = post_order[post_r];
  int p = in_l;
  while (in_order[p] != root) {
    p++;
  }
  int in_l_children_count = p - in_l;
  l_child[root] = construct(in_l, p - 1, post_l, post_l + in_l_children_count - 1);
  r_child[root] = construct(p + 1, in_r, post_l + in_l_children_count, post_r - 1);
  return root;
}

void dfs(int u, int sum) {
  sum += u;
  if (!l_child[u] && !r_child[u]) {
    if (sum < leaf_path_sum || (sum == leaf_path_sum && u < leaf_value)) {
      leaf_value = u;
      leaf_path_sum = sum;
    }
  }
  if (l_child[u]) {
    dfs(l_child[u], sum);
  }
  if (r_child[u]) {
    dfs(r_child[u], sum);
  }
}

int main() {
  while (read_input(in_order)) {
    read_input(post_order);
    construct(0, n - 1, 0, n - 1);
    leaf_path_sum = 100000000;
    dfs(post_order[n - 1], 0);
    cout << leaf_value << endl;
  }
  
  return 0;
}
